import index from "../../../router";
<template>
  <div class="goodsBox">
    <el-form ref="ruleForm" :model="ruleForm" label-width="20%" status-icon>
      <el-row :gutter="150">
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <!--<el-form-item label="商品属性组" prop="desc">
            <el-button size="small" @click="attributeBtn" :disabled="disableIinput">选择</el-button>
          </el-form-item>-->
          <el-form-item label="商品属性">
            <template v-if="ruleForm.isUsedSalesProp === 1">
              <div>销售属性：<el-button :disabled="disableIinput" size="mini" type="primary" style="cursor: pointer" @click="yesAttr">选择</el-button></div>
              <ul class="yesAttrStyle">
                <li v-for="(item,index) in properties" :key="index">
                  <div>
                    {{ item.propName }}
                    <label v-for="(value,index) in item.itemPropOptions" :key="index"><input :value="value" v-model="item.selectedValues" type="checkbox" @change="changeFun" >{{ value.optionValue }}</label>
                  </div>
                  <el-button size="mini" type="danger" plain @click="delYesAttr(item)">删除</el-button>
                </li>
              </ul>
            </template>
            <template>
              <div>非销售属性：<el-button :disabled="disableIinput" size="mini" type="primary" style="cursor: pointer" @click="noAttr">选择</el-button></div>
              <ul class="yesAttrStyle">
                <li v-for="(item,index) in noproperties" :key="index">
                  <div>
                    {{ item.propName }}
                    <label v-for="(value,index) in item.itemPropOptions" :key="index"><input :value="value" v-model="item.radiosValues" type="radio" @change="changeFun" >{{ value.optionValue }}</label>
                  </div>
                  <el-button size="mini" type="danger" plain @click="delNoAttr(item)">删除</el-button>
                </li>
              </ul>
            </template>
          </el-form-item>
          <div v-show="ruleForm.isUsedSalesProp === 0">
            <el-form-item :rules="[{ required: true,message: '请输入SKU成本价格', trigger: 'blur'}]" label="SKU成本价" prop="sku.originalPrice">
              <el-input v-model="ruleForm.sku.originalPrice" :disabled="disableIinput" size="small" type="text" placeholder="请输入SKU成本价"/>
            </el-form-item>
            <el-form-item :rules="[{ required: true, message: '请输入兑换积分', trigger: 'blur'}]" label="兑换积分" prop="sku.integralPrice">
              <el-input v-model="ruleForm.sku.integralPrice" :disabled="disableIinput" size="small" type="text" placeholder="请输入兑换积分"/>
            </el-form-item>
            <el-form-item :rules="[{ required: true, message: '请输入库存', trigger: 'blur'}]" label="库存(件)" prop="sku.skuDiscount">
              <el-input v-model="ruleForm.sku.skuDiscount" :disabled="disableIinput" size="small" type="text" placeholder="请输入库存"/>
            </el-form-item>
            <!--<el-form-item label="商品积分比例折扣" prop="desc">
              <el-input size="small" type="text" v-model="ruleForm.desc" :disabled="disableIinput" placeholder="请输入SEO关键字">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>-->
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-form-item label="启用销售属性" prop="isUsedSalesProp">
            <el-radio-group v-model="ruleForm.isUsedSalesProp">
              <el-radio :label="0" :disabled="disableIinput">不启用</el-radio>
              <el-radio :label="1" :disabled="disableIinput">启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-show="ruleForm.isUsedSalesProp === 1">
      <el-tab-pane label="SKU信息">
        <!--表格-->
        <el-card style="margin-top: 10px">
          <div class="table-wrapper">
            <el-table v-loading="!skus" :stripe="true" :data="skus" border empty-text="暂无数据">

              <el-table-column type="index" label="序号" header-align="center" align="center"/>

              <el-table-column v-for="(item,index) in dataValTableOne" v-if="item.selectedValues.length>0" :key="index" :label="item.propName" align="center">
                <template slot-scope="scope">
                  {{ getValueName(scope.row,item) }}
                </template>
              </el-table-column>

              <el-table-column align="center" label="兑换积分">
                <template slot-scope="scope">
                  <el-input :disabled="disableIinput" v-model="scope.row.integralPrice" size="mini" type="number" />
                </template>
              </el-table-column>

              <el-table-column align="center" label="国际条码类型">
                <template slot-scope="scope">
                  <el-input :disabled="disableIinput" v-model="scope.row.barcodeType" size="mini" />
                </template>
              </el-table-column>

              <el-table-column align="center" label="国际条码">
                <template slot-scope="scope">
                  <el-input :disabled="disableIinput" v-model="scope.row.barcode" size="mini"/>
                </template>
              </el-table-column>

              <el-table-column align="center" label="自定编号">
                <template slot-scope="scope">
                  <el-input :disabled="disableIinput" v-model="scope.row.sellerSkuNo" size="mini" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="外部编号">
                <template slot-scope="scope">
                  <el-input :disabled="disableIinput" v-model="scope.row.outerNo" size="mini" />
                </template>
              </el-table-column>

              <el-table-column align="center" label="商品积分比例折扣(%)">
                <template slot-scope="scope">
                  <el-input :disabled="disableIinput" v-model="scope.row.skuDiscount" size="mini" />
                </template>
              </el-table-column>

              <el-table-column align="center" label="SKU成本价格(元)">
                <template slot-scope="scope">
                  <el-input :disabled="disableIinput" v-model="scope.row.originalPrice" size="mini" type="number" />
                </template>
              </el-table-column>

              <el-table-column align="center" label="SKU图片">
                <template slot-scope="scope">
                  <upLoadImgsku :idx="scope.$index" @emitSuccessImg="successImg"/>
                  <img :src="scope.row.defaultPicUrl" width="70px" height="70px">
                </template>
              </el-table-column>

            </el-table>
          </div>
        </el-card>
      </el-tab-pane>

    </el-tabs>

    <!--弹框-->
    <el-dialog
      :visible.sync="dialogState"
      :title="dialogTitle"
      :close-on-click-modal="false"
      :before-close="handleClose"
      top="5vh"
      width="40%">
      <template>
        <el-tree
          v-loading="!threeList"
          v-if="isRouterAlive"
          ref="tree"
          :default-expanded-keys="threeCheck"
          :default-checked-keys="threeCheck"
          :data="threeList"
          :props="defaultProps"
          show-checkbox
          node-key="propId"
          highlight-current/>
      </template>
      <div class="btns-wrapper">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="small" @click="submmitFun">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as commodity from '../../../api/commodity'
import upLoadImgsku from '../../../components/UpLoadImg_sku'
export default {
  components: { upLoadImgsku },
  /* eslint-disable vue/require-prop-types */
  props: ['type', 'editorData'],
  data() {
    return {
      // 商品销售属性
      properties: [],
      skus: [],
      // 商品非销售属性
      noproperties: [],
      // 弹框
      dialogType: 1, // 1--销售属性  2--非销售属性
      dialogState: false,
      // 输入禁用
      disableIinput: false,
      // 列表数据
      dataValTableOne: [],
      ruleForm: {
        isUsedSalesProp: 0,
        attrNo: '',
        // 商品不启用时sku信息
        sku: {
          skuId: null,
          originalPrice: '',
          integralPrice: '',
          skuDiscount: '',
          formName: 'ruleForm'
        }
      },
      // Three树
      isRouterAlive: true,
      threeList: null,
      threeCheck: [],
      defaultProps: {
        label: 'propName',
        disabled: this.disabledFn
      }
    }
  },
  computed: {
    dialogTitle() {
      if (this.dialogType === 1) {
        return '请选择销售属性'
      }
      if (this.dialogType === 2) {
        return '请选择非销售属性'
      } else {
        return '查看'
      }
    }
  },
  beforeMount() {
    if (this.type !== 1) {
      this.ruleForm.isUsedSalesProp = this.editorData.isUsedSalesProp
      this.skuList()
      this.yesAttrList()
      this.noAttrList()
    }
    if (this.type === 3) {
      this.disableIinput = true
    }
  },
  methods: {
    // 销售属性
    // 获取最初始的数据结构
    submmitFun() {
      if (this.type === 1) {
        const parr = this.$refs.tree.getCheckedNodes()
        if (this.dialogType === 1) {
          for (const val of parr) {
            val.selectedValues = []
          }
          this.properties = parr // 处理初试数据
        } else if (this.dialogType === 2) {
          for (const val of parr) {
            val.radiosValues = ''
          }
          this.noproperties = parr
        }
        this.dialogState = false
      } else {
        const parr = this.$refs.tree.getCheckedNodes()
        if (this.dialogType === 1) {
          for (const val of parr) {
            val.selectedValues = []
          }
          for (let i = 0; i < parr.length; i++) {
            for (let j = 0; j < this.properties.length; j++) {
              if (parr[i].propId === this.properties[j].propId) {
                parr.splice(i, 1)
              }
            }
          }
          for (const val of parr) {
            this.properties.push(val)
          }
        } else if (this.dialogType === 2) {
          for (const val of parr) {
            val.radiosValues = ''
          }
          for (let i = 0; i < parr.length; i++) {
            for (let j = 0; j < this.noproperties.length; j++) {
              if (parr[i].propId === this.noproperties[j].propId) {
                parr.splice(i, 1)
              }
            }
          }
          for (const val of parr) {
            this.noproperties.push(val)
          }
        }
        this.dialogState = false
      }
      this.threeList = null
    },
    // 复选框事件给表格头部赋值  表格数据this.skus
    changeFun() {
      this.dataValTableOne = this.properties
      this.reBuild()
    },
    // 给表格重建数据
    reBuild() {
      var vm = this
      var oriSkus = JSON.parse(JSON.stringify(this.skus))
      var vmSkus = this.skus = []
      var propertyChecked = []
      var skuCount = 1
      var ori = []
      vm.properties.forEach(function(index) {
        var selectValues = index.selectedValues
        if (selectValues.length > 0) {
          propertyChecked.push(index)
          skuCount = skuCount * selectValues.length
          ori.push(selectValues)
        }
      })
      var ret = this.descartes(ori)
      for (var i = 0; i < ret.length; i++) {
        var sku = {
          skuName: '',
          integralPrice: '',
          barcodeType: 'EAM',
          barcode: '',
          sellerSkuNo: '',
          outerNo: '',
          skuDiscount: '',
          originalPrice: '',
          defaultPicUrl: '',
          isUsedSalesProp: 1,
          skuPropVos: []
        }
        ret[i].forEach(function(item) {
          sku.skuPropVos.push({
            optionValue: item.optionValue,
            optionId: item.optionId,
            propId: item.propId
          })
          sku.skuName += ' ' + item.optionValue
        })
        if (oriSkus.length >= ret.length) {
          sku.integralPrice = oriSkus[i].integralPrice
          sku.barcodeType = 'EAM'
          sku.barcode = oriSkus[i].barcode
          sku.sellerSkuNo = oriSkus[i].sellerSkuNo
          sku.outerNo = oriSkus[i].outerNo
          sku.skuDiscount = oriSkus[i].skuDiscount
          sku.originalPrice = oriSkus[i].originalPrice
          sku.defaultPicUrl = oriSkus[i].defaultPicUrl
          sku.isUsedSalesProp = 1
        } else {
          if (i < oriSkus.length) {
            sku.integralPrice = oriSkus[i].integralPrice
            sku.barcodeType = 'EAM'
            sku.barcode = oriSkus[i].barcode
            sku.sellerSkuNo = oriSkus[i].sellerSkuNo
            sku.outerNo = oriSkus[i].outerNo
            sku.skuDiscount = oriSkus[i].skuDiscount
            sku.originalPrice = oriSkus[i].originalPrice
            sku.defaultPicUrl = oriSkus[i].defaultPicUrl
            sku.isUsedSalesProp = 1
          } else {
            sku.integralPrice = ''
            sku.barcodeType = 'EAM'
            sku.barcode = ''
            sku.sellerSkuNo = ''
            sku.outerNo = ''
            sku.skuDiscount = ''
            sku.originalPrice = ''
            sku.defaultPicUrl = ''
            sku.isUsedSalesProp = 1
          }
        }
        vmSkus.push(sku)
      }
    },
    // 表格显示属性值
    getValueName(sku, property) {
      var valueName = ''
      if (sku.skuPropVos !== undefined && property.selectedValues !== undefined) {
        sku.skuPropVos.forEach(function(item) {
          var _this = item
          if (item.propId === property.propId) {
            property.selectedValues.forEach(function(item) {
              if (_this.optionId === item.optionId) {
                valueName = item.optionValue
                return false
              }
            })
          }
        })
      }
      return valueName
    },
    // 算法规则
    descartes(list) {
      // parent上一级索引;count指针计数
      var point = {}
      var result = []
      var pIndex = null
      var tempCount = 0
      var temp = []
      // 根据参数列生成指针对象
      for (const index in list) {
        if (typeof list[index] === 'object') {
          point[index] = { 'parent': pIndex, 'count': 0 }
          pIndex = index
        }
      }
      // 单维度数据结构直接返回
      if (pIndex == null) {
        return list
      }
      // 动态生成笛卡尔积
      /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
      while (true) {
        for (var index in list) {
          tempCount = point[index]['count']
          temp.push(list[index][tempCount])
        }
        // 压入结果数组
        result.push(temp)
        temp = []
        // 检查指针最大值问题
        /*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
        while (true) {
          if (point[index]['count'] + 1 >= list[index].length) {
            point[index]['count'] = 0
            pIndex = point[index]['parent']
            if (pIndex == null) {
              return result
            }
            // 赋值parent进行再次检查
            index = pIndex
          } else {
            point[index]['count']++
            break
          }
        }
      }
    },
    // 筛选销售属性
    yesAttr() {
      this.dialogType = 1
      this.dialogState = true
      this.isRouterAlive = true
      this.threeCheck = []
      this.AttrList(1)
    },
    noAttr() {
      this.dialogType = 2
      this.dialogState = true
      this.isRouterAlive = true
      this.threeCheck = []
      this.AttrList(0)
    },
    AttrList(data) {
      const param = {
        current: 1,
        size: 3000,
        isSellingProp: data
      }
      commodity.isgetAttrGroupList(param).then(res => {
        this.threeList = res.data.data.records
        if (data === 1) {
          for (const val of this.properties) {
            this.threeCheck.push(val.propId)
          }
        } else if (data === 0) {
          for (const val of this.noproperties) {
            this.threeCheck.push(val.propId)
          }
        }
      })
    },
    // 图片上传
    successImg(data) {
      for (let i = 0; i < this.skus.length; i++) {
        if (i === data.index) {
          this.skus[i].defaultPicUrl = data.imgurl
        }
      }
    },
    // sku列表
    skuList() {
      const that = this
      commodity.getSkuList(this.editorData.itemId).then(res => {
        if (res.data.code === 1) {
          if (res.data.code === 1) {
            const skus = res.data.data
            for (const val of skus) {
              if (val.isDefaultCreated === 1) {
                that.ruleForm.sku.originalPrice = skus[0].originalPrice
                that.ruleForm.sku.integralPrice = skus[0].integralPrice
                that.ruleForm.sku.skuDiscount = skus[0].skuDiscount
                that.ruleForm.sku.skuId = skus[0].skuId
              } else {
                that.skus.push(val)
              }
            }
          }
        }
      })
    },
    // 销售属性反显
    yesAttrList() {
      const param = {
        itemId: this.editorData.itemId,
        type: 1
      }
      commodity.getAttrList(param).then(res => {
        if (res.data.code === 1) {
          const parr = res.data.data
          for (const val of parr) {
            val.selectedValues = []
            for (const data of val.choose) {
              val.selectedValues.push(data)
            }
          }
          this.properties = parr
          this.dataValTableOne = this.properties
        }
      })
    },
    // 非销售属性反显
    noAttrList() {
      const param = {
        itemId: this.editorData.itemId,
        type: 0
      }
      commodity.getAttrList(param).then(res => {
        if (res.data.code === 1) {
          const parr = res.data.data
          for (const val of parr) {
            val.radiosValues = val.choose[0]
          }
          this.noproperties = parr
        }
      })
    },
    // 删除销售属性
    delYesAttr(data) {
      if (data.selectedValues.length === 0 || data.selectedValues === undefined || data.selectedValues === null) {
        var _this = this
        this.properties.forEach(function(item, index) {
          if (data.propId === item.propId) {
            _this.properties.splice(index, 1)
          }
        })
      } else {
        this.$message({
          showClose: true,
          message: '警告哦，请取消属性所选中的值在进行删除~',
          type: 'warning',
          duration: 3000
        })
      }
    },
    // 删除非销售属性
    delNoAttr(data) {
      if (data.radiosValues === '') {
        var _this = this
        this.noproperties.forEach(function(item, index) {
          if (data.propId === item.propId) {
            _this.noproperties.splice(index, 1)
          }
        })
      } else {
        this.$message({
          showClose: true,
          message: '警告哦，请取消属性所选中的值在进行删除~',
          type: 'warning',
          duration: 3000
        })
      }
    },
    // tree禁用
    disabledFn(data, node) {
      if (this.threeCheck.includes(data.propId)) {
        return true
      } else {
        return false
      }
    },
    handleClose() {
      this.isRouterAlive = false
      this.dialogState = false
      this.threeList = null
    },
    incrementTotal() {
      const formName = 'ruleForm'
      if (this.ruleForm.isUsedSalesProp === 0) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('skusubmitType', ['skuinfor', true, this.ruleForm, this.noproperties, 'no'])
          } else {
            this.$emit('skusubmitType', ['skuinfor', false, this.ruleForm, this.noproperties, 'no'])
            return false
          }
        })
      } else {
        this.$emit('skusubmitType', ['', this.skus, this.noproperties, 'yes'])
        this.$refs[formName].clearValidate()
      }
    }
    /* handleEdit(index, row) {
    @change="handleEdit(scope.$index, scope.row)"
      this.$emit('skusubmitType', ['', this.skus])
    }*/
  }
}
</script>

<style type="text/scss" lang="scss">
  .goodsBox{
    .el-form-item{
      margin-bottom: 12px;
    }
    .el-form-item__label{
      line-height: 18px;
      margin-top: 9px;
    }
    .el-form-item__error{
      top: 90%;
    }
    .el-pagination{
      text-align: right;
    }
    .el-dialog__header{
      margin-bottom: 0;
    }
    .el-table th{
      padding: 5px 0;
    }
  }

</style>
<style type="text/scss" lang="scss" scoped>
  ul,li{
    list-style: none;
  }
  .yesAttrStyle{
    li{
      padding: 0 5px;
      border-radius: 5px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      button{
        padding: 0 10px;
        height: 25px;
        display: none;
      }
    }
    li:hover{
      background-color: rgba(217, 221, 201, 0.37);
    }
    li:hover button{
      display: block;
    }
  }
</style>
